# utils/orders.py
import random
from datetime import datetime
from flask import abort
from flask_login import current_user


def gen_order_no() -> str:
    # 形如 20251104-6位随机
    return datetime.utcnow().strftime('%Y%m%d') + '-' + str(random.randint(100000, 999999))


def calc_amount_cents(cart_items) -> int:
    # cart_items: [{'title':..., 'sku':..., 'qty':..., 'unit_price_cents':...}, ...]
    return sum(int(i['qty']) * int(i['unit_price_cents']) for i in cart_items)


def require_admin():
    if not (getattr(current_user, 'is_admin', False) or getattr(current_user, 'is_superuser', False)):
        abort(403)
